package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.User;
import com.itheima.vo.UserInfo;
import com.itheima.vo.UserInfoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.tuil.ConstantUtil;
import com.itheima.tuil.JwtUtil;
import com.itheima.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {
    @DubboReference
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //保存用户
    public ResponseEntity save(User user) {
        long userId = userService.save(user);
        return ResponseEntity.ok(userId);
    }

    //根据手机号查询
    public ResponseEntity findByPhone(String phone) {
        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user);
    }


    public void sendSms(String phone) {
        //生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code = "123456";
        //调用阿里云发送短信
//        smsTemplate.sendSms(phone, code);//todo 产品上线后在使用
        //将验证码存储到redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE +phone,code, Duration.ofMinutes(5));
    }


    public ResponseEntity regAndLogin(String phone, String verificationCode) {
        //1取出redis中验证吗
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        //2对比验证码
        if (!StrUtil.equals(verificationCode,codeFromRedis)) {
           return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        //3根据手机号查询user对象
        User user = userService.findByPhone(phone);
        Boolean isNew;
        if (user != null) {
            //3-1 查到了，是老用户
            isNew = false;
        } else {
            //3-2  没查到，是新用户/并保存新用户
            isNew = true;
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            long userId = userService.save(user);
            user.setId(userId);
        }
        //4 制作jtw的token
            //先将密码设置成null然后再将user转换成token
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);
        //5在redis中存储token和用户信息，设置有效时间是7天
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        //清空redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);
        //6返回结果 token isNew
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("isNew", isNew);
        resultMap.put("token", token);
        return ResponseEntity.ok(resultMap);
    }

    @DubboReference
    private UserInfoService userInfoService;

    //完善用户信息
    public void saveUserInfo(UserInfo userInfo, String token) {
        //1. 解析token获取user对象
        User user = findByToken(token);
        //2. 封装userInfo(userId)
        userInfo.setId(user.getId());
        //3. 调用rpc保存
        userInfoService.saveUserInfo(userInfo);
    }

    //抽取公共方法用来查询token
    public User findByToken(String token) {
        //接收redis中的token
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        //判断是否有token(用stringUtil工具类)
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        //如果不为空就将token转成user对象
        User user = JSON.parseObject(json, User.class);

        //续期登陆时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        return user;
    }

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    //设用用户头像
    public ResponseEntity saveHeadPhoto(MultipartFile headPhoto, String token) throws IOException {
        //1. 人脸检测
        boolean checkFace = aipFaceTemplate.detect(headPhoto.getBytes());
        if (checkFace==false) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        //2. 将图片上传到oss
        String picUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //3. 封装UserInfo
        UserInfo userInfo = new UserInfo();
        //3.1 用户id
        User user = findByToken(token);
        userInfo.setId(user.getId());
        //3.2 用户头像
        userInfo.setAvatar(picUrl);
        //3.3 用户封面
        userInfo.setCoverPic(picUrl);
        //4. 调用rpc更新
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findByUserInfoVo(Long userID) {
        //根据userInfo查询
        UserInfo userInfo = userInfoService.findById(userID);

        //封装userInfo
        UserInfoVo vo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, vo);

        //返回userInfoVo
        return ResponseEntity.ok(vo);
    }

    public void updateUserInfo(UserInfo userInfo, String token) {
        //解析token获取userId
        User user = findByToken(token);
        //将userId设置到userInfo
        userInfo.setId(user.getId());
        //调用rpc更新
        userInfoService.update(userInfo);
    }
}
